<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Test Login</title>
    <script src="http://cdn.staticfile.org/axios/0.24.0/axios.js"></script>
    <script src="http://cdn.staticfile.org/blueimp-md5/1.0.1/js/md5.js"></script>
    <script src="http://npmcdn.com/parse/dist/parse.js"></script>
</head>
<body>


<form onsubmit="return reg(this)" >
  <h3>注册</h3>
  用户名: <input type="text" name="username" />
  密码: <input type="password" name="password" />
  <input type="submit" value="注册" />
</form>

<form onsubmit="return login(this)" >
    <h3>登录</h3>
    用户名: <input type="text" name="username" />
    密码: <input type="password" name="password" />
    <input type="submit" value="登录" />
</form>


<form onsubmit="return loginWithParse(this)" >
    <h3>登录并连接Parse</h3>
    用户名: <input type="text" name="username" />
    密码: <input type="password" name="password" />
    <input type="submit" value="登录" />
</form>

<script>
    function reg(form){
        console.log("reg");
        const username=form.username.value;
        const password=form.password.value;
        axios.post("/user/reg",{username,password}).then(ok=>{
            alert("注册成功")
        }).catch(e=>{
            alert("注册失败："+e.response.data.error)
        });
        return false;
    }

    function login(form){
        console.log("login");
        const username=form.username.value;
        const password=form.password.value;
        const salt="lims_v5";
        const password_md5 = md5(password+salt);
        axios.post("/user/login",{username,password_md5}).then(ok=>{
            alert("登录成功")
        }).catch(e=>{
            alert("登录失败："+e.response.data.error)
        });
        return false;
    }

    function loginWithParse(form){
        console.log("login");
        const username=form.username.value;
        const password=form.password.value;
        const salt="lims_v5";
        const password_md5 = md5(password+salt);
        axios.post("/user/login",{username,password_md5}).then(ok=>{
            alert("登录成功（第一步）");
            const myAuthData = {
                    id: username,  // Required field. Used to uniquely identify the linked account.
                password_md5
            };
            Parse.initialize("APPLICATION_ID");
            Parse.serverURL = '/parse';
            const user = new Parse.User();
            user.linkWith('lims_auth', { authData: myAuthData }).then(user=>{
                alert("连接成功（第二步）");
                console.log(Parse.User.current().toJSON())
            }).catch(e=>{
                alert("连接失败:"+e.toString())
            });
        }).catch(e=>{
            alert("登录失败："+(e.response && e.response.data.error))
        });
        return false;
    }
</script>

</body>
</html>